package DAO;

import java.io.BufferedWriter;
import java.io.File;

import java.io.FileWriter;
import java.io.IOException;

import java.net.URL;
import java.util.Scanner;

import Modele.CollectionFavoris;
import Modele.Factory;





public class DAOFavoris 
{
    /**
     * Pour serialiser notre collection de favoris
     * @param listefav
     */
   
    public static void saveFavoris(CollectionFavoris listefav){
       
       try {            
              
               FileWriter fw = new FileWriter("favoris.txt", false);
               BufferedWriter output = new BufferedWriter(fw);
             
            try {
                if (listefav != null){
                  output.write(listefav.toString());
                  output.flush();
                }
            } finally {
           
                try {
                    
                        output.close();
                } finally {
                 
                    fw.close();
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    /**
     * Pour deserialiser notre liste de favoris
     * @return
     */
    
    public static CollectionFavoris loadFavoris() { 

        CollectionFavoris listefav = new CollectionFavoris();
        
     
        Scanner fichier;
        String line = null;
  
        try {
            fichier = new Scanner(new File("favoris.txt"));    
                      
            while (fichier.hasNextLine()) {
                
                line = fichier.nextLine();
               
                if (line != null){
                  
                    String[] splitArray = line.split(" ");
                    String nom = splitArray[0];
                    URL url = new URL(splitArray[1]);
                    listefav.addFavoris(Factory.getFavoris(nom, url));
                }
            }

            fichier.close();        
         
            return listefav;
        
        } catch (IOException  e) {
            return listefav;
        }

    }
}
